/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package business;

import entity.Event;
import entity.Group;
import java.security.Principal;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import entity.User;
import entity.Visibility;
import entity.Group;
import entity.Participant;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.NamedQuery;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

/**
 *
 * @author Alessandro
 */
@Stateless
public class UserManager implements Serializable{
    
    
    @PersistenceContext
    private EntityManager em;
    
    @Inject
    Principal principal;
    
    public void save (User user){
        user.setGroupName(Group.USER);
        user.setVisibility(Visibility.PRIVATE);
        em.persist(user);   
    }
    
    public User getLoggedUser(){
        return em.find(User.class, principal.getName());
    }

    public String changeVisibility(){
        User user = this.getLoggedUser();
        System.out.println("ciao, sono user manager, cambio visibilita che per ora è"+user.getVisibility());
        Query vis = em.createNamedQuery("changeVisibility2");
        if (user.getVisibility().equals(Visibility.PUBLIC)) {
            vis.setParameter("visibility", Visibility.PRIVATE);
        } else {
            vis.setParameter("visibility", Visibility.PUBLIC);
        }
        vis.setParameter("email", user.getEmail());
        vis.executeUpdate();
        System.out.println("ora la visibilità è "+this.getLoggedUser().getVisibility().toString());
        return "profile";
    }
    /*
    TODO: check deleted events!!!!!! if an event is flagged to be deleted it won't
          be shown in the calendar FUCK YOU!!!!! Miglierina figlio di puttana
    */
    public List<Event> loadCalendar() {
        System.out.println("adesso flusho");
        em.flush();
        /*
            dunno why???!! need this coz it won't update the events created in the same session
        */
        em.getEntityManagerFactory().getCache().evictAll(); 
        User user = this.getLoggedUser();
        System.out.println("ciao, sono user manager, carico eventi per "+ user.getEmail());
        Collection<Participant> cal = user.getParticipantCollection();
        List<Event> calendar = new ArrayList<>();
        for(Participant p : cal){
            calendar.add(p.getEvent1());
        }
        return calendar;
    }
}
